package com.yc.filter;

import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zwei
 * @create 2024-06-19 17:28
 */
//@WebFilter("/admin/*")
public class AdminFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpSession session=req.getSession();
        if (session.getAttribute("admin")!=null){
            filterChain.doFilter(req,resp);
        }else {
            Map<String,Object>map=new HashMap<String,Object>();
            map.put("code",0);
            map.put("error","访问后台权限不够或没有登录");
            resp.setContentType(("text/json;charset=utf-8"));
            PrintWriter out=resp.getWriter();
            Gson g=new Gson();
            out.println(g.toJson(map));
            out.flush();
            out.close();
        }
    }

    @Override
    public void destroy() {

    }
}
